package com.genesis.yunnanji;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.IdRes;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.genesis.yunnanji.activity.BaseActivity;
import com.genesis.yunnanji.activity.StoreWeb;
import com.genesis.yunnanji.activity.Sup;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.fragment.ExplorationRoomFragment;
import com.genesis.yunnanji.fragment.HomePage;
import com.genesis.yunnanji.fragment.Land;
import com.genesis.yunnanji.fragment.Market;
import com.genesis.yunnanji.fragment.Personal;
import com.genesis.yunnanji.fragment.Strategy;
import com.genesis.yunnanji.utils.OkGoUpdateHttpUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarTab;
import com.roughike.bottombar.OnTabReselectListener;
import com.roughike.bottombar.OnTabSelectListener;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;

public class MainActivity extends BaseActivity {

    private long exitTime = 0;
    private Personal fmPersonal;
    private Strategy fmStrategy;
    private HomePage fmHomePage;
    private Market fmMall;
    private Land fmLand;
    private Sup fmSup;
    private ExplorationRoomFragment explorationRoomFragment;
    @ViewInject(R.id.bottom_navigation_bar)
    private BottomBar mNavigationBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_main);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.main_color), 0);
        setDefaultFragment();
        Update();
    }

    @Override
    protected void setUpView() {
        requestSomePermission();
        mNavigationBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(@IdRes int tabId) {
                FragmentManager fm = MainActivity.this.getSupportFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                switch (tabId) {
                    case R.id.homepage:
                        if (fmHomePage == null) {
                            fmHomePage = HomePage.newInstance("首页");
                        }
                        transaction.replace(R.id.vp_content, fmHomePage);
                        break;
                    case R.id.news:
                        Intent intent = new Intent(context, StoreWeb.class);
                        if (genesisUtils.isLogin()) {
                            intent.putExtra("url", GenesisApiConfig.HOST + "/Mall/Index/index.html" + GenesisApiConfig.FROM_APP + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
                            startActivity(intent);
                        } else {
                            intent.putExtra("url", GenesisApiConfig.HOST + "/Mall/Index/index.html" + GenesisApiConfig.FROM_APP);
                            startActivity(intent);
                        }
                        if (fmMall == null) {
                            if (genesisUtils.isLogin()) {
                                fmMall = Market.newInstance(GenesisApiConfig.HOST + "/Mall/Index/index.html" + GenesisApiConfig.FROM_APP + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
                            } else {
                                fmMall = Market.newInstance(GenesisApiConfig.HOST + "/Mall/Index/index.html" + GenesisApiConfig.FROM_APP);
                            }
                        }
                        transaction.replace(R.id.vp_content, fmMall);
                        break;
                    case R.id.sup:
//                        if (fmSup == null) {
//                            fmSup = Sup.newInstance("");
//                        }
//                        transaction.replace(R.id.vp_content, fmSup);
                        if (explorationRoomFragment == null) {
                            explorationRoomFragment = ExplorationRoomFragment.newInstance("");
                        }
                        transaction.replace(R.id.vp_content, explorationRoomFragment);
                        break;
                    case R.id.raider://文旅地产
                        if (fmLand == null) {
                            if (genesisUtils.isLogin()) {
                                fmLand = Land.newInstance("http://m.jinzhanji.com/Wenlv/index.html" + GenesisApiConfig.FROM_APP + GenesisApiConfig.APP_TOKEN + genesisUtils.getAppToken());
                            } else {
                                fmLand = Land.newInstance("http://m.jinzhanji.com/Wenlv/index.html" + GenesisApiConfig.FROM_APP);
                            }
                        }
                        transaction.replace(R.id.vp_content, fmLand);
                        break;
                    case R.id.me:
                        if (fmPersonal == null) {
                            fmPersonal = Personal.newInstance("我");
                        }
                        transaction.replace(R.id.vp_content, fmPersonal);
                        break;
                }
                transaction.commit();
            }
        });

    }

    /**
     * 运行权限申请
     */
    private void requestSomePermission() {
        AndPermission.with(MainActivity.this)
                .requestCode(100)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE,
                        Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CONTACTS).callback(listener)
                .send();
    }


    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            Log.i("Permision", "权限onSucceed:" + grantedPermissions.toString());
            if (grantedPermissions.contains("android.permission.ACCESS_FINE_LOCATION")) {
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {
                AndPermission.defaultSettingDialog(MainActivity.this, 400)
                        .setTitle("权限申请失败")
                        .setMessage("您拒绝了我们必要的一些权限，如需正常使用，请在设置中授权！")
                        .setPositiveButton("好，去设置").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.this.finish();
                    }
                }).show();
            }
        }
    };

    /**
     * 双击返回键退出应用
     */
    @Override
    public void onBackPressed() {
        long currtTime = System.currentTimeMillis();
        if (currtTime - exitTime > 2000) {
            Toasty.info(context, "再次点击返回退出应用", Toast.LENGTH_SHORT).show();
            exitTime = currtTime;
            return;
        }
        //退出程序
        this.finish();
    }

    /**
     * 设置默认Fragment
     */
    private void setDefaultFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        fmHomePage = HomePage.newInstance("新闻");
        transaction.replace(R.id.vp_content, fmHomePage).commit();
    }

    public void Update() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("versioncode", context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode + "");
            new UpdateAppManager
                    .Builder()
                    //当前Activity
                    .setActivity(MainActivity.this)
                    .setParams(params)
                    .setTopPic(R.mipmap.top6)
                    .setUpdateUrl(GenesisApiConfig.HOST + GenesisApiConfig.UPDATE)
                    .setPost(false)
                    .setTargetPath(path)
                    //实现httpManager接口的对象
                    .setHttpManager(new OkGoUpdateHttpUtil())
                    .setThemeColor(getResources().getColor(R.color.main_color))
                    .build()
                    .checkNewApp(new UpdateCallback() {
                        @Override
                        protected UpdateAppBean parseJson(String json) {
                            UpdateAppBean updateAppBean = new UpdateAppBean();
                            Gson gson = new Gson();
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                if (jsonObject.optInt("code") == 2) {
                                    updateAppBean = gson.fromJson(jsonObject.optJSONObject("data").toString(), UpdateAppBean.class);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            return updateAppBean;
                        }

                        @Override
                        protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                            updateAppManager.showDialogFragment();
                        }
                    });
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

}
